import { DeleteOutlined, InboxOutlined } from '@ant-design/icons';
import { Button, Progress, Upload, UploadProps, message, Spin } from 'antd';
import axios from 'axios';
import { useEffect, useState } from 'react';
import { LoadingOutlined } from '@ant-design/icons';
const antIcon = (
  <LoadingOutlined
    style={{
      fontSize: 24,
    }}
    spin
  />
);
const { Dragger } = Upload;

const VideoUpload: React.FC = (props: any) => {
  const [messageApi, contextHolder] = message.useMessage();
  const key = 'updatable';
  const [progress, setProgress] = useState(0);
  const [fileList, setFileList] = useState([]);
  const [displayVideo, setDisplayVideo] = useState(false);
  const [videoResponse, setVideoResponse] = useState({});
  useEffect(() => {
    if (Object.keys(props.fileResponse).length > 0) {
      setDisplayVideo(true);
      setVideoResponse(JSON.parse(JSON.stringify(props.fileResponse).replace('httpurl', 'path')));
    }
  }, [props.fileResponse]);
  const openLoadingMessage = () => {
    messageApi.open({
      type: 'loading',
      content: '正在上传视频，可能时间会比较长，请您耐心等待。',
      duration: 0,
    });
  };
  const openSuccessMessage = () => {
    messageApi.open({
      key,
      type: 'success',
      content: '上传成功!',
      duration: 2,
    });
  };
  const openErrorMessage = () => {
    messageApi.open({
      key,
      type: 'error',
      content: '上传失败！',
      duration: 2,
    });
  };
  const dragger_props: UploadProps = {
    name: 'file',
    onChange(info) {},
    onDrop(e) {
      console.log('Dropped files', e.dataTransfer.files);
    },

    async customRequest(param) {
      const { onSuccess, onError, file, onProgress } = param;
      const config = {
        headers: { 'content-type': 'multipart/form-data' },
        onUploadProgress: (event) => {
          console.log(event.loaded, event.total);

          const percent = Math.floor((event.loaded / event.total) * 100);
          setProgress(percent);
          if (percent === 100) {
            setTimeout(() => setProgress(0), 1000);
          }
          onProgress({ percent: (event.loaded / event.total) * 100 });
        },
      };
      let formData = new FormData();
      formData.append('file', file);
      // openLoadingMessage();
      // const hide = message.loading('正在上传视频，可能时间会比较长，请您耐心等待。', 0);

      const videoUrl = '/api/v1/video/formUpload';

      formData.append('file', file);

      try {
        {
          contextHolder;
        }

        const response = await axios.post(videoUrl, formData, config);
        onSuccess(response);
        // props.setVideoInfo(response.data.data)
        setDisplayVideo(true);
        // openSuccessMessage();
        // message.destroy()

        // hide();
        setVideoResponse(response.data.data);
        props.setResponse(response.data.data);
      } catch (error) {
        // hide();
        // openErrorMessage();
        onError({ error });
      }
    },
  };
  // const onChange: UploadProps['onChange'] = async ({ file,fileList: newFileList }) => {
  //     await setFileList(newFileList);
  //     // props.form.setFieldValue('uploadImgs', props.fileList);
  //   };
  // const deleteVideo = (file) => {
  // let responseSrc = ''
  // let currentFiles = [];
  // if(file.response){
  //     responseSrc = file.response.data.data[0].src;
  //     currentFiles = props.fileResponse;

  // }else{
  //     responseSrc = file.src;
  //     currentFiles = props.fileList;
  // }
  // currentFiles.splice(currentFiles.findIndex(item=>item.src === responseSrc),1);
  // //     props.setResponse(currentFiles);

  // }
  const deleteVideo = () => {
    setDisplayVideo(false);
    // setVideoInfo({});
  };
  return (
    <div>
      {contextHolder}
      <Dragger
        {...dragger_props}
        name="file"
        style={{
          display: displayVideo ? 'none' : 'block',
        }}
        // listType="picture-card"
        fileList={[]}
        // onChange={onChange}
        // onPreview={onPreview}
        // onRemove={onRemove}
      >
        <p className="ant-upload-drag-icon">
          <InboxOutlined />
        </p>
        <p className="ant-upload-text">点击或拖动文件上传</p>
        <p className="ant-upload-hint">
          支持单个或批量上传。严禁上传包含色情、暴力、反动等相关违法信息的文件。
        </p>

        {progress > 0 ? <Progress percent={progress}></Progress> : null}
      </Dragger>

      <div
        style={{
          display: displayVideo ? 'block' : 'none',
        }}
      >
        <video width="320" height="240" controls src={videoResponse.path}>
          {/* <source src={videoResponse.path} type="video/mp4"/> */}
        </video>

        <Button type="link" danger onClick={deleteVideo}>
          <DeleteOutlined />
        </Button>
      </div>
    </div>
  );
};
export default VideoUpload;
